import rand from "./rand";

export default class Coords {
  private coords: { x: number; y: number; }[] = [];
  constructor() { }

  init(x: number, y: number, count: number): this {
    for (let i = count; i >= 0; --i)
      this.coords.push({ x, y })
    return this;
  }

  forward(x: number, y: number): this {
    if (!this.coords.length) return this;
    for (let i = this.coords.length - 1; i > 0; --i) {
      this.coords[i].x = this.coords[i - 1].x;
      this.coords[i].y = this.coords[i - 1].y;
    }
    this.coords[0].x = x;
    this.coords[0].y = y;
    return this;
  }

  random_curve(ctx: CanvasRenderingContext2D, x: number, y: number) {
    const len = this.coords.length;
    if (len <= 1) return;

    let idx = Math.round((rand(0, len))) % len;
    ctx.beginPath();
    ctx.moveTo(this.coords[idx].x, this.coords[idx].y);
    while ((--idx) >= 0) {
      ctx.quadraticCurveTo(
        this.coords[idx].x,
        this.coords[idx].y,
        this.coords[idx - 1]?.x ?? x,
        this.coords[idx - 1]?.y ?? y,
      )
    }
  }
}
